import Mn from 'backbone.marionette';
import {
    getOpt
} from 'tools.js';
import DateWidget from 'widgets/DateWidget.js';
import InputWidget from 'widgets/InputWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';
import CatalogComponent from 'common/views/CatalogComponent.js';
import TvaProductFormMixin from 'base/views/TvaProductFormMixin.js';
import Radio from 'backbone.radio';

var template = require('./templates/TaskLineFormView.mustache');

const TaskLineFormView = Mn.View.extend(TvaProductFormMixin).extend({
    id: 'task_line_form',
    template: template,
    behaviors: [ModalFormBehavior],
    regions: {
        'order': '.order',
        'description': '.description',
        'date': '.date',
        'cost': '.cost',
        'quantity': '.quantity',
        'unity': '.unity',
        'tva': '.tva',
        'product_id': '.product_id',
        'catalogContainer': '#catalog-container'
    },
    ui: {
        main_tab: 'ul.nav-tabs li:first a'
    },
    // Bubble up child view events
    //
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:modified',
        'catalog:insert': 'catalog:insert'
    },
    modelEvents: {
        'set:product': 'refreshForm',
        'change:tva': 'refreshTvaProductSelect',
    },
    initialize(options) {
        this.session = Radio.channel('session');
        this.config = Radio.channel('config');
        this.workunit_options = this.config.request(
            'get:options',
            'workunits'
        );
        this.tva_options = this.config.request(
            'get:options',
            'tvas'
        );
        this.product_options = this.config.request(
            'get:options',
            'products',
        );
        this.all_product_options = this.config.request(
            'get:options',
            'products'
        );
        this.compute_mode = this.config.request('get:options', 'compute_mode');
        this.section = options['section'];
    },
    isAddView: function () {
        return !getOpt(this, 'edit', false);
    },
    templateContext: function () {
        return {
            dateRequired: this.section['date'],
            title: this.getOption('title'),
            add: this.isAddView()
        };
    },
    showOrderfield() {
        this.showChildView(
            'order',
            new InputWidget({
                value: this.model.get('order'),
                field_name: 'order',
                type: 'hidden',
            })
        );
    },
    showDescriptionField() {
        this.showChildView(
            'description',
            new TextAreaWidget({
                value: this.model.get('description'),
                title: "Description",
                field_name: "description",
                tinymce: true,
                required: true,
                cid: this.model.cid
            })
        );
    },
    showDateField() {
        this.showChildView(
            'date',
            new DateWidget({
                value: this.model.get('date'),
                default_value: null,
                title: "Date d'exécution",
                field_name: "date",
                required: true
            })
        );
    },
    showCostField() {
        const field_config = this.section['cost'];
        let label = "Prix unitaire ";
        if (this.compute_mode == 'ttc') {
            label += "TTC"
        } else {
            label += "HT"
        }
        this.showChildView(
            'cost',
            new InputWidget({
                value: this.model.get('cost'),
                title: label,
                field_name: "cost",
                required: true,
                addon: "€",
                editable: field_config['edit']
            })
        );
    },
    showQuantityField() {
        const field_config = this.section['quantity'];
        this.showChildView(
            'quantity',
            new InputWidget({
                value: this.model.get('quantity'),
                title: "Quantité",
                field_name: "quantity",
                required: true,
                editable: field_config['edit']
            })
        );
    },
    showUnityField() {
        this.showChildView(
            'unity',
            new SelectWidget({
                options: this.workunit_options,
                title: "Unité",
                value: this.model.get('unity'),
                field_name: 'unity',
                id_key: 'value'
            })
        );
    },
    showTvaField() {
        const field_config = this.section['tva'];
        const tva_value = this.model.get('tva');
        this.showChildView(
            'tva',
            new SelectWidget({
                options: this.tva_options,
                title: "TVA",
                value: tva_value,
                field_name: 'tva',
                id_key: 'value',
                required: true,
                editable: field_config['edit']
            })
        );
    },
    refreshForm: function () {
        this.showOrderfield();
        this.showDescriptionField();

        let hasDate = this.section['date'];
        if (hasDate) {
            this.showDateField();
        }
        this.showCostField();
        this.showQuantityField();
        this.showUnityField();
        this.showTvaField();

        this.refreshTvaProductSelect();
        if (this.isAddView()) {
            this.getUI('main_tab').tab('show');
        }
    },
    getCurrentTvaId() {
        /* Override the default method of the TvaProductFormMixin
         */
        let tva_id;
        if (this.model.has('tva')) {
            let tva_value = this.model.get('tva');
            let tva_object = _.findWhere(this.tva_options, {
                value: parseFloat(tva_value)
            });
            if (tva_object) {
                tva_id = tva_object.id;
            }
        }
        return tva_id;
    },
    onRender: function () {
        this.refreshForm();
        if (this.isAddView()) {
            this.showChildView(
                'catalogContainer',
                new CatalogComponent({
                    query_params: {
                        type_: 'product'
                    },
                    multiple: true,
                    url: AppOption['catalog_tree_url'],
                })
            );
        }
    }
});
export default TaskLineFormView;